import { Http, IAppAuthService, IHttp, IParam, LogUtil } from 'ibz-core';
import { getCookie, setCookie } from 'qx-util';

/**
 * 应用权限服务类
 *
 * @export
 * @class AppAuthService
 */
export class AppAuthService implements IAppAuthService {
  /**
   * 网络请求对象
   *
   * @private
   * @type {Http}
   * @memberof AppAuthService
   */
  readonly http: IHttp = Http.getInstance();

  /**
   * 唯一实例
   *
   * @private
   * @static
   * @memberof AppAuthService
   */
  private static readonly instance = new AppAuthService();

  /**
   * 获取唯一实例
   *
   * @static
   * @return {*}  {AppAuthService}
   * @memberof AppAuthService
   */
  public static getInstance(): AppAuthService {
    return AppAuthService.instance;
  }

  /**
   * @description 登录(后续需考虑运行平台)
   * @param {{ loginname: string, password: string }} _data 登录名，密码
   * @return {*}  {Promise<IParam>}
   * @memberof AppAuthService
   */
  public async login(_data: { loginname: string; password: string }): Promise<IParam> {
    const response = await this.http.post(App.Environment.RemoteLogin, _data, true);
    const { status, data } = response;
    if (status == 200) {
      this.setExpiredDate(new Date(data.expirdate));
    }
    return response;
  }

  /**
   * @description 登出
   * @return {*}  {Promise<IParam>}
   * @memberof AppAuthService
   */
  public async logout(): Promise<IParam> {
    const response = await await this.http.get(App.Environment.RemoteLogout);
    return response;
  }

  /**
   * @description 刷新TOKEN
   * @param {IParam} data 请求相关数据
   * @return {*}  {Promise<boolean>}
   * @memberof IAppAuthService
   */
  public async refreshToken(data: IParam): Promise<boolean> {
    if (
      data &&
      (data.url == '/v7/refreshToken' ||
        data.url == '/v7/login' ||
        data.url == '/appdata' ||
        data.url.startsWith('./assets'))
    ) {
      return true;
    }
    try {
      const response = await Http.getInstance().get('/v7/refreshToken');
      if (response && response.status === 200) {
        const data = response.data;
        this.setExpiredDate(new Date(data.expirdate));
        if (data) {
          setCookie('ibzuaa-token', data.token, 7, true);
        }
        return true;
      } else {
        LogUtil.log('刷新token出错');
        return false;
      }
    } catch (error) {
      return false;
    }
  }

  /**
   * @description 判断TOKEN是否过期
   * @param {Date} date
   * @return {*}  {boolean}
   * @memberof AppAuthService
   */
  isTokenExpired(date: Date): boolean {
    if (this.getExpiredDate()) {
      if (App.Environment) {
        return date.getTime() > this.getExpiredDate().getTime() - App.Environment.refreshTokenTime;
      } else {
        return false;
      }
    } else {
      this.setExpiredDate(new Date());
      return false;
    }
  }

  /**
   * @description 获取TOKEN过期时间
   * @return {*}  {Date}
   * @memberof AppAuthService
   */
  getExpiredDate(): Date {
    const expiredTime = getCookie('ibzuaa-expired');
    return new Date(Number(expiredTime));
  }

  /**
   * @description 设置TOKEN过期时间
   * @param {Date} date 时间
   * @memberof AppAuthService
   */
  setExpiredDate(date: Date): void {
    setCookie('ibzuaa-expired', date.getTime().toString(), 7, true);
  }

  /**
   * @description 获取用户访问权限
   * @param {IParam} viewModel 视图模型
   * @return {*}  {boolean}
   * @memberof AppAuthService
   */
  public async getUserAccessAuth(viewModel: IParam): Promise<boolean> {
    const token = getCookie('ibzuaa-token');
    switch (viewModel.accUserMode) {
      // 未启用访问用户模式
      case 0:
        return true;
      // 匿名用户
      case 1:
        return token ? false : true;
      // 登录用户
      case 2:
        return token ? true : false;
      // 匿名用户及登录用户
      case 3:
        return true;
      // 登录用户且拥有指定资源能力
      case 4:
        const UIServiceBase = await App.getUIService().getService({}, {});
        return UIServiceBase.getResourceOPPrivs(viewModel.accessKey);
      default:
        return true;
    }
  }
}
